package com.lzy.wzy.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzy.wzy.config.MyPasswordEncoder;
import com.lzy.wzy.constant.MyConstant;
import com.lzy.wzy.mapper.UserMapper;
import com.lzy.wzy.model.*;
import com.lzy.wzy.result.ResponseCode;
import com.lzy.wzy.result.Result;
import com.lzy.wzy.service.AdminService;
import com.lzy.wzy.token.MyUsernamePasswordToken;
import com.lzy.wzy.utils.PatternUtils;
import com.lzy.wzy.utils.WorkOrderUtils;
import com.lzy.wzy.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.flowable.engine.IdentityService;
import org.flowable.idm.api.Group;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Service
@Slf4j
public class AdminServiceImp implements AdminService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkOrderUtils workOrderUtils;

    @Autowired
    private MyPasswordEncoder myPasswordEncoder;

    @Autowired
    private IdentityService identityService;

    /*
     * @Author wzy
     * @Description //TODO 添加用户
     * @Date 2021/8/20 17:23
     * @Param * @param: userVo
     * @return com.lzy.wzy.result.Result<org.apache.poi.ss.formula.functions.T>
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<T> addUser(UserVo userVo) {
        if (userMapper.queryUserCountByUserName(userVo.getUsername()) > 0) {
            return Result.failure("此账户已存在");
        }
        if (PatternUtils.verifyFoxEmail(userVo.getEmail().trim())) {
            return Result.failure("邮箱格式错误");
        }
        int roleId = Integer.parseInt(userVo.getRoleId());
        int departmentId = Integer.parseInt(userVo.getDepartmentId());
        Integer count = userMapper.matchRolesAndDepartments(departmentId, roleId);
        if (count < 1) {
            return Result.failure("部门与角色不匹配");
        }
        String departmentName = userMapper.getDepartmentNameByDepartmentId(departmentId);
        String role = userMapper.getRoleNameByRoleId(roleId);
        if (MyConstant.Role.SUPER_ADMINISTRATOR.equals(role)) {
            return Result.failure("不可添加超级管理员");
        }
        if (MyConstant.Role.ADMIN.equals(role)) {
            MyUsernamePasswordToken token = (MyUsernamePasswordToken) SecurityContextHolder.getContext().getAuthentication();
            String userId = String.valueOf(token.getPrincipal());
            if (workOrderUtils.checkSuperAdmin(userId)) {
                return Result.failure("不可添加管理员");
            }
        }
        User user = new User();
        user.setName(userVo.getName().trim());
        user.setUsername(userVo.getUsername().trim());
        user.setPassword(myPasswordEncoder.encode("123456"));
        user.setDepartment(departmentName);
        user.setEmail(userVo.getEmail().trim());
        user.setRole(role);
        user.setCreateTime(LocalDateTime.now());
        user.setUserUuid(UUID.randomUUID().toString().replace("-", ""));
        UserRoleBean userPermissionBean = new UserRoleBean(user.getUserUuid(), roleId);
        if (userMapper.addUser(user) > 0 && userMapper.bindUserAndRole(userPermissionBean) > 0) {
            String gId=String.valueOf(roleId);
            log.info("新增用户成功");
            if (identityService.createGroupQuery().groupId(gId)==null) {
                Group group = identityService.newGroup(gId);
                group.setName(role);
                identityService.saveGroup(group);
            }
            org.flowable.idm.api.User fUser = identityService.newUser(user.getUserUuid());
            fUser.setFirstName(user.getName());
            fUser.setTenantId(gId);
            identityService.saveUser(fUser);
            identityService.createMembership(fUser.getId(), gId);
            return Result.success("新增用户成功");
        }
        return Result.failure("新增用户失败");
    }

    /*
     * @Author wzy
     * @Description //TODO 查询用户信息
     * @Date 2021/8/20 17:23
     * @Param * @param: pageSize
     * @param: pageNum
     * @return com.lzy.wzy.result.Result<com.github.pagehelper.PageInfo<com.lzy.wzy.model.User>>
     **/
    @Override
    public Result<PageInfo<User>> queryAllUserInfo(Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);

        PageInfo<User> pageInfo = new PageInfo<>(userMapper.queryAllUserInfo());

        return Result.success(pageInfo);
    }

    /*
     * @Author wzy
     * @Description //TODO 修改用户信息
     * @Date 2021/8/20 17:23
     * @Param * @param: userVo
     * @return com.lzy.wzy.result.Result<org.apache.poi.ss.formula.functions.T>
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<T> modifyUserInfo(ModifyUserVo userVo) {
        int roleId = Integer.parseInt(userVo.getRoleId());
        int departmentId = Integer.parseInt(userVo.getDepartmentId());
        if (userMapper.matchRolesAndDepartments(departmentId, roleId) < 1) {
            return Result.failure("部门和职位不匹配");
        }
        User user = new User();
        BeanUtils.copyProperties(userVo, user);
        String roleName = userMapper.getRoleNameByRoleId(roleId);
        String departmentName = userMapper.getDepartmentNameByDepartmentId(departmentId);
        if (MyConstant.Role.SUPER_ADMINISTRATOR.equals(roleName)) {
            return Result.failure("不可修改");
        }
        user.setRole(roleName);
        user.setDepartment(departmentName);
        String userId = userVo.getUserUuid();
        MyUsernamePasswordToken token = (MyUsernamePasswordToken) SecurityContextHolder.getContext().getAuthentication();
        String curId = String.valueOf(token.getPrincipal());
        if (userMapper.getUserCountByUserUuid(userId) > 0
                && workOrderUtils.checkAdmin(userId, curId)
                && userMapper.modifyUserInfo(user) > 0) {
            userMapper.updateRoleUserMapping(userId, roleId);
            log.info("用户修改成功");
            return Result.success("修改成功");
        }
        return Result.failure("修改失败");
    }

    /*
     * @Author wzy
     * @Description //TODO 加载管理员页面职位和部门信息
     * @Date 2021/8/20 17:24
     * @Param * @param:
     * @return com.lzy.wzy.result.Result<com.lzy.wzy.vo.AdminPageInitVo>
     **/
    @Override
    public Result<AdminPageInitVo> adminPageInitLoad() {
        AdminPageInitVo initVo = new AdminPageInitVo();
        List<RoleBean> allRole = userMapper.getAllRole();
        List<DepartmentBean> allDepartment = userMapper.getAllDepartment();
        initVo.setRoles(allRole);
        initVo.setDepartments(allDepartment);
        return Result.success(initVo);
    }

    /*
     * @Author wzy
     * @Description //TODO 获取所有职位
     * @Date 2021/8/20 17:24
     * @Param * @param:
     * @return com.lzy.wzy.result.Result<java.util.List<com.lzy.wzy.model.RoleBean>>
     **/
    @Override
    public Result<List<RoleBean>> doGetAllRole() {
        return Result.success(userMapper.getAllRole());
    }

    /*
     * @Author wzy
     * @Description //TODO 获取所有部门
     * @Date 2021/8/20 17:24
     * @Param * @param:
     * @return com.lzy.wzy.result.Result<java.util.List<com.lzy.wzy.model.DepartmentBean>>
     **/
    @Override
    public Result<List<DepartmentBean>> doGetAllDepartment() {
        return Result.success(userMapper.getAllDepartment());
    }

    /*
     * @Author wzy
     * @Description //TODO 删除用户
     * @Date 2021/8/20 17:24
     * @Param * @param: userUuid
     * @return com.lzy.wzy.result.Result<org.apache.poi.ss.formula.functions.T>
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<T> deleteUsers(String userUuid) {
        MyUsernamePasswordToken token = (MyUsernamePasswordToken) SecurityContextHolder.getContext().getAuthentication();
        String userId = String.valueOf(token.getPrincipal());
        if (userMapper.getUserCountByUserUuid(userUuid) > 0
                && workOrderUtils.checkAdmin(userUuid, userId)
                && userMapper.deleteUserById(userUuid) > 0) {
            return Result.success("删除成功");
        }
        return Result.failure("删除失败");
    }

    /*
     * @Author wzy
     * @Description //TODO 条件查询用户
     * @Date 2021/8/20 17:25
     * @Param * @param: pageSize
     * @param: pageNum
     * @param: searchValue
     * @return com.lzy.wzy.result.Result<com.github.pagehelper.PageInfo<com.lzy.wzy.model.User>>
     **/
    @Override
    public Result<PageInfo<User>> doMultiConditionQueryUser(int pageSize, int pageNum, String searchValue) {
        PageHelper.startPage(pageNum, pageSize);

        PageInfo<User> pageInfo = new PageInfo<>(userMapper.getUserByUsernameOrName(searchValue));

        return Result.success(pageInfo);
    }

    /*
     * @Author wzy
     * @Description //TODO 通过职位查询用户信息
     * @Date 2021/8/20 17:25
     * @Param * @param: pageSize
     * @param: pageNum
     * @param: roleId 职位id
     * @return com.lzy.wzy.result.Result<com.github.pagehelper.PageInfo<com.lzy.wzy.model.User>>
     **/
    @Override
    public Result<PageInfo<User>> doQueryUserInformationByRole(int pageSize, int pageNum, String roleId) {
        String role = userMapper.getRoleNameByRoleId(Integer.parseInt(roleId));
        if (null != role) {
            PageHelper.startPage(pageNum, pageSize);
            PageInfo<User> pageInfo = new PageInfo<>(userMapper.getUserInfoByRole(role));
            return Result.success(pageInfo);
        }
        return Result.failure("此职位不存在");
    }

    /*
     * @Author wzy
     * @Description //TODO 查询此部门下所有员工
     * @Date 2021/8/20 17:26
     * @Param * @param: pageSize
     * @param: pageNum
     * @param: departmentId
     * @return com.lzy.wzy.result.Result<com.github.pagehelper.PageInfo<com.lzy.wzy.model.User>>
     **/
    @Override
    public Result<PageInfo<User>> doQueryUserInformationByDepartment(int pageSize, int pageNum, String departmentId) {
        String department = userMapper.getDepartmentNameByDepartmentId(Integer.parseInt(departmentId));
        if (null != department) {
            PageHelper.startPage(pageNum, pageSize);
            PageInfo<User> pageInfo = new PageInfo<>(userMapper.getUserInfoByDepartment(department));
            return Result.success(pageInfo);
        }
        return Result.failure("此部门不存在");
    }

    /*
     * @Author wzy
     * @Description //TODO 添加新职位
     * @Date 2021/8/20 17:26
     * @Param * @param: roleName
     * @param: permissionIds
     * @param: departmentId
     * @return com.lzy.wzy.result.Result<org.apache.poi.ss.formula.functions.T>
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<T> doAddNewPosition(String roleName, List<Integer> permissionIds, int departmentId) {
        if (null == userMapper.getRoleByRoleName(roleName)
                && userMapper.saveNewPositionInfo(roleName) > 0) {
            //获取新增的职位id
            int roleId = userMapper.getRoleByRoleName(roleName);
            List<RolePermissionBean> list = new ArrayList<>();
            RolePermissionBean permissionBean;
            for (Integer permissionId : permissionIds) {
                permissionBean = new RolePermissionBean(roleId, permissionId);
                list.add(permissionBean);
            }
            if (!(userMapper.matchRolesAndDepartments(departmentId, roleId) < 1
                    && userMapper.addNewPositionToDepartment(roleId, departmentId) > 0
                    && userMapper.addPermissionsToTheRole(list) == list.size()))
                return Result.failure("添加失败");
        }
        return Result.success("添加成功");
    }

    /*
     * @Author wzy
     * @Description //TODO 添加新部门
     * @Date 2021/8/20 17:26
     * @Param * @param: departmentName
     * @return com.lzy.wzy.result.Result<org.apache.poi.ss.formula.functions.T>
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<T> doAddNewDepartment(String departmentName) {
        if (userMapper.getDepartmentByDepartmentName(departmentName) == 0 && userMapper.saveNewDepartment(departmentName) > 0) {
            return Result.success("添加成功");
        }
        return Result.failure("添加失败");
    }

    /*
     * @Author wzy
     * @Description //TODO  获取此部门下所有权限信息
     * @Date 2021/8/20 17:27
     * @Param * @param: departmentId
     * @return com.lzy.wzy.result.Result<java.util.List<com.lzy.wzy.model.PermissionBean>>
     **/
    @Override
    public Result<List<PermissionBean>> doGetPermissionUnderTheDepartment(String departmentId) {
        if (PatternUtils.checkDigitId(departmentId)) {
            return Result.invalidFormat();
        }
        return Result.success(userMapper.getPermissionUnderTheDepartment(Integer.parseInt(departmentId)));
    }

    /*
     * @Author wzy
     * @Description //TODO 获取此部门下所有职位信息
     * @Date 2021/8/20 17:27
     * @Param * @param: departmentId 部门id
     * @return com.lzy.wzy.result.Result<java.util.List<com.lzy.wzy.model.RoleBean>>
     **/
    @Override
    public Result<List<RoleBean>> doGetAPositionUnderTheDepartment(String departmentId) {
        return Result.success(userMapper.getAPositionUnderTheDepartment(Integer.parseInt(departmentId)));
    }

    /*
     * @Author wzy
     * @Description //TODO 删除职位信息
     * @Date 2021/8/20 17:28
     * @Param * @param: roleId 职位id
     * @return com.lzy.wzy.result.Result<org.apache.poi.ss.formula.functions.T>
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<T> doDeleteRoleInfo(int roleId) {
        if (userMapper.getRoleMapping(roleId) == 0
                && userMapper.deleteRole(roleId) > 0
                && userMapper.deleteRolePermissionMapping(roleId) > 0) {
            return Result.success();
        }
        return Result.failure("删除失败");
    }


    /*
     * @Author wzy
     * @Description //TODO 重置密码
     * @Date 2021/8/27 16:42
     * @Param * @param: userId
     * @return com.lzy.wzy.result.Result<org.apache.poi.ss.formula.functions.T>
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<T> doResetPassword(String userId) {
        MyUsernamePasswordToken token = (MyUsernamePasswordToken) SecurityContextHolder.getContext().getAuthentication();
        String curId = (String) token.getPrincipal();
        if (userMapper.getUserCountByUserUuid(userId) > 0
                && workOrderUtils.checkAdmin(userId, curId)
                && userMapper.updatePassword(myPasswordEncoder.encode("123456"), userId) > 0) {
            return Result.success();
        }
        return Result.failure();
    }

    /*
     * @Author wzy
     * @Description //TODO 获取用户姓名，账户，角色信息
     * @Date 2021/12/8 17:45
     * @Param * @param:
     * @return com.lzy.wzy.result.Result<com.lzy.wzy.vo.UserPartInfoVo>
     **/
    @Override
    public Result<UserPartInfoVo> doGetUserPartInfo() {
        MyUsernamePasswordToken token = (MyUsernamePasswordToken) SecurityContextHolder.getContext().getAuthentication();
        String userId = (String) token.getPrincipal();
        return Result.success(userMapper.getUserPartInfo(userId));
    }

    /*
     * @Author wzy
     * @Description //TODO 获取所有工号
     * @Date 2021/12/8 17:45
     * @Param * @param:
     * @return com.lzy.wzy.result.Result<java.util.List<com.lzy.wzy.vo.KeyValueVo>>
     **/
    @Override
    public Result<List<KeyValueVo>> doGetAllJobNumber() {
        return Result.success(userMapper.getAllJobNumber());
    }

    /*
     * @Author wzy
     * @Description //TODO 禁用用户
     * @Date 2021/12/8 17:45
     * @Param * @param: userId
     * @return com.lzy.wzy.result.Result<java.lang.Integer>
     **/
    @Override
    public Result<Integer> doDisableUser(String userId) {
        MyUsernamePasswordToken token = (MyUsernamePasswordToken) SecurityContextHolder.getContext().getAuthentication();
        String curId = (String) token.getPrincipal();
        if (curId.equals(userId)) {
            return Result.failure("非法操作");
        }
        if (!workOrderUtils.checkSuperAdmin(userId)) {
            return Result.failure("不可禁用超级管理员");
        }
        Integer count = userMapper.getUserCountByUserUuid(userId);
        if (count > 0) {
            if (userMapper.updateUserStatus(1, userId, 0) > 0) {
                return Result.to(ResponseCode.SUCCESS.getCode(), "禁用成功", 1);
            } else {
                return Result.failure("禁用失败,或已被禁用");
            }
        }
        return Result.failure("用户不存在");
    }

    /*
     * @Author wzy
     * @Description //TODO 用户解封
     * @Date 2021/12/8 17:46
     * @Param * @param: userId
     * @return com.lzy.wzy.result.Result<java.lang.Integer>
     **/
    @Override
    public Result<Integer> doUnlockTheUser(String userId) {
        MyUsernamePasswordToken token = (MyUsernamePasswordToken) SecurityContextHolder.getContext().getAuthentication();
        String curId = (String) token.getPrincipal();
        if (curId.equals(userId)) {
            return Result.failure("非法操作");
        }
        if (!workOrderUtils.checkSuperAdmin(userId)) {
            return Result.failure("非法操作");
        }
        Integer count = userMapper.getUserCountByUserUuid(userId);
        if (count > 0) {
            if (userMapper.updateUserStatus(0, userId, 1) > 0) {
                return Result.to(ResponseCode.SUCCESS.getCode(), "解禁成功", 0);
            } else {
                return Result.failure("解禁失败,或已解禁");
            }
        }
        return Result.failure("用户不存在");
    }


    /*
     * @Author wzy
     * @Description //TODO 邮箱绑定
     * @Date 2021/12/20 17:25
     * @Param * @param: email
     * @return com.lzy.wzy.result.Result<org.apache.poi.ss.formula.functions.T>
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<T> doBingdingEmail(String email) {
        MyUsernamePasswordToken token = (MyUsernamePasswordToken) SecurityContextHolder.getContext().getAuthentication();
        String userId = (String) token.getPrincipal();
        String var1 = userMapper.getEmailById(userId);
        if (StringUtils.isNotBlank(var1)) {
            if (!var1.equals(email)) {
                if (userMapper.updateEmail(email, userId) > 0) {
                    return Result.success("邮箱更新成功");
                } else {
                    Result.failure("更新失败");
                }
            } else {
                Result.failure("两次邮箱一致，修改失败");
            }
        } else {
            if (userMapper.updateEmail(email, userId) > 0) {
                return Result.success("邮箱更新成功");
            } else {
                Result.failure("更新失败");
            }
        }
        return Result.success("邮箱更新成功");
    }
}
